package com.foreveross.proxyip.util;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;

import com.foreveross.proxyip.core.pools.AvailablePool;
import com.foreveross.proxyip.core.pools.PoolsManager;
import com.foreveross.proxyip.core.redis.PiRedisExecption;
import com.foreveross.proxyip.entity.ProxyIpBean;
import com.foreveross.proxyip.infra.PageData;

public class PoolPageUtil {

	@Autowired
	PoolsManager poolsManager;
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public PageData loadPageData(AvailablePool pool ,PageData pageData) throws Exception{
		if(pageData==null){
			pageData = new PageData();
		}
		int pageIndex = pageData.getPageIndex();
		int pageLen = pageData.getPageLen();
		if(pageIndex==0){
			pageData.setPageIndex(PageData.DEFAULT_PAGEINDEX);
			pageIndex = pageData.getPageIndex();
		}
		if(pageLen==0){
			pageData.setPageLen(PageData.DEFAULT_PAGELEN);
			pageLen = pageData.getPageLen();
		}
		if(pool==null||pool.size()==0){
			return pageData;
		}
		List resultList = null;
//		List<ProxyIpBean> proxyIps = new Vector<ProxyIpBean>();
		
		
//		this.orderByRetrieveTimeDesc(ips);
		int count = this.getPageCount(pool, pageLen);//总页数
		//start：开始坐标，end：结束坐标
		long start = 0,end = 0;
		
		start = (pageIndex-1)*pageLen;
		if(pageIndex==count){//最后一次
			end = pool.size();
		}else{
			end = (pageIndex-1)*pageLen+pageLen;
		}
		resultList = new Vector(pool.poolIpMap.subList(start, end));
		pageData.setDataSize(pool.size());
		pageData.setPageCount(count);
		pageData.setPageIndex(pageIndex);
		pageData.setPageLen(pageLen);
//		pageData.setState(1)
		pageData.setResult(resultList);
		
		return pageData;
	}
	
	public Integer getPageCount(AvailablePool pool ,Integer rowNum) throws PiRedisExecption{
		Long page = (pool.size()/rowNum);
		int count = page.intValue() ;//总页数
		if(count != 0){
			count = pool.size()%rowNum!=0?count+1:count;
		}else{
			count = 1;
		}
		return count;
	}
	
	public void orderByRetrieveTimeDesc(List<ProxyIpBean> ips){
		 Collections.sort(ips, new Comparator<ProxyIpBean>() {
			@Override
			public int compare(ProxyIpBean arg0, ProxyIpBean arg1) {
				if( arg1.getRetrieveTime()==null){
					return -1;
				}
				if(arg0.getRetrieveTime()==null){
					return 1;
				}
				if(arg0.getRetrieveTime().after(arg1.getRetrieveTime())){
					return -1;
				}else{
					return 1;
				}
			}
		});
	}
}
